﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace MVC3AsyncFileUploadDemo.Controllers
{
	public class HomeController : Controller
	{
		public ActionResult Index()
		{
			ViewBag.Message = "Welcome to ASP.NET MVC!";

			return View();
		}

		[HttpPost]
		public WrappedJsonResult UploadImage(HttpPostedFileWrapper imageFile)
		{
			// we check for the image

			if (imageFile == null || imageFile.ContentLength == 0)
			{
				// we did not find an image so we return an invalid result
				return new WrappedJsonResult
				{
					Data = new
					{
						IsValid = false,
						Message = "No file was uploaded.",
						ImagePath = string.Empty
					}
				};
			}

			// we found the image so we store it on the disk
			var fileName = String.Format("{0}.jpg", Guid.NewGuid().ToString()); // we give the file a name
			var imagePath = Path.Combine(Server.MapPath(Url.Content("~/Uploads")), fileName); // we build the file path

			imageFile.SaveAs(imagePath); // we save the current file under a specific name and location given above

			return new WrappedJsonResult
			{
				// we build up the wrapped json result that will help us identify the uploaded file
				Data = new
				{
					IsValid = true,
					Message = string.Empty,
					ImagePath = Url.Content(String.Format("~/Uploads/{0}", fileName)) // we set the image path so we can take it from javascript and display it easy
				}
			};
		}
	}
}
